package com.cms.biz.queryAnalyse.query;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.stereotype.Repository;

import com.common.util.EMPSQLUtil;
import com.efounder.builder.base.data.DataSetUtils;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.sql.JConnection;
import com.efounder.sql.JStatement;
import com.enums.EMPQueryParamEnum;
import com.mrp.persistence.queryAnalyse.pageQuery.bean.EMPPageQuery;
import com.pub.util.EMPLimitConvertUtil;
import com.pub.util.StringFunction;


/**
 * <p>Title: 项目查询分析</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
@Repository
public class EMPCCNRQuery {

	@Autowired
	private JdbcTemplate                  jdbcTemplate;
	
	protected     String                   msTableName = "";

	
	public JResponseObject QueryObject(JParamObject PO){
		JConnection         conn = null;
		JStatement          stmt = null;
		EFDataSet   queryDataset = null;
		EFRowSet     queryRowset = EFRowSet.getInstance();
		JResponseObject       RO = null;
		try {
			conn = JConnection.getInstance(jdbcTemplate.getDataSource().getConnection());
			conn.setAutoCommit(true);
			stmt = conn.createStatement();
			
			// 获取查询数据
			queryDataset = queryDataObject(stmt, PO);
			queryRowset.setExtProperty(EMPQueryParamEnum.PAGEQUERY, PO.getValue(EMPQueryParamEnum.PAGEQUERY, null));
			queryRowset.setDataSet(EMPQueryParamEnum.QUERYRESULT, queryDataset);
			// 封装返回数据
		   	RO = new JResponseObject(queryRowset, 0);
		} catch(Exception ce) {
			ce.printStackTrace();
			RO = new JResponseObject(null, -1, ce);
		} finally {
			try {
				stmt.executeUpdate("drop table "+msTableName);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			EMPSQLUtil.closeAllResources(null, stmt, conn);
		}
		return RO;
	}
	
	/**
	 * 组织数据的过程
	 * @throws Exception
	 * @return TreeTableDataManager
	 */
	private EFDataSet queryDataObject(Statement stmt, JParamObject po) throws Exception{
		EFDataSet   queryDataset = null;
		//创建临时表
	    createTempTable(stmt);
	    
	    //取出原始数据
	    getOriginData(stmt, po);
	    
	    //创建临时表
	    queryDataset = convertDataSet(stmt, po);
		return queryDataset;
	}
	
	/**
	 * 创建临时表
	 * @throws Exception
	 */
	private void createTempTable(Statement stmt) throws Exception{
	    msTableName = "CCNR"+StringFunction.getTempStr(6);
	    String        strSql = "";
	    
	    String tempTableBody = " F_ID          varchar(1)           default ''   null,"	         				
	         				 + " F_XMBH        varchar(255)         default ''   null,"
	         				 + " F_XMMC        varchar(255)         default ''   null,"
	         				 + " F_CPBH        varchar(255)         default ''   null,"
	         				 + " F_CPMC        varchar(255)         default ''   null,"
	         				 + " F_SCSL        decimal(30,2)        default 0    null,"
	         				 + " F_CCSL        decimal(30,2)        default 0    null,"
	         				 + " F_SYSL        decimal(30,2)        default 0    null";
	    strSql = "create table " + msTableName + "(" + tempTableBody + ")";
	    stmt.execute(strSql);
	  }
	  
	/**
	 * 逐级汇总数据
	 * @throws Exception
	 */
	public void getOriginData(Statement stmt, JParamObject po) throws Exception {
		String              strSql = "";
		String              F_CPBH = po.GetValueByParamName("F_CPBH", "");
		String              F_XMBH = po.GetValueByParamName("F_XMBH", "");

		//插入生产数量
		strSql = " insert into " + msTableName + " (F_ID, F_XMBH,F_CPBH,F_SCSL)"
		       + " select '0', F_XMBH,F_CPBH,F_SCSL"
		       + " from SCTZMX"		      
		       + " where F_XMBH like '" + F_XMBH + "%' and F_CPBH like '" + F_CPBH + "%' and "	
		       + " exists(select 1 from SCTZXX where SCTZXX.F_KJQJ = SCTZMX.F_KJQJ and SCTZXX.F_DJBH = SCTZMX.F_DJBH and " 
		       + " SCTZXX.F_DJZT = '1') and "
		       + " exists(select 1 from FLOW_TASK_END_LIST where FLOW_TASK_END_LIST.BIZ_DATE = SCTZMX.F_KJQJ and " 
		       + " FLOW_TASK_END_LIST.BIZ_DJBH = SCTZMX.F_DJBH and FLOW_TASK_END_LIST.BIZ_GUID = SCTZMX.F_GUID and FLOW_TASK_END_LIST.FLOW_ID = 'SCTZ_FLOW')";
		stmt.execute(strSql);
		
		//插入出厂数量
		strSql = " insert into " + msTableName + " (F_ID, F_XMBH,F_CPBH,F_CCSL)"
		       + " select '0', F_XMBH,F_CPBH,F_CCSL"
		       + " from CCTZMX"		      
		       + " where F_XMBH like '" + F_XMBH + "%' and F_CPBH like '" + F_CPBH + "%' and "	
		       + " exists(select 1 from CCTZXX where CCTZXX.F_KJQJ = CCTZMX.F_KJQJ and CCTZXX.F_DJBH = CCTZMX.F_DJBH and " 
		       + " CCTZXX.F_DJZT = '1') and "
		       + " exists(select 1 from FLOW_TASK_END_LIST where FLOW_TASK_END_LIST.BIZ_DATE = CCTZMX.F_KJQJ and " 
		       + " FLOW_TASK_END_LIST.BIZ_DJBH = CCTZMX.F_DJBH and FLOW_TASK_END_LIST.BIZ_GUID = CCTZMX.F_GUID and FLOW_TASK_END_LIST.FLOW_ID = 'CCTZ_FLOW')";
		stmt.execute(strSql);
	}
	
	public EFDataSet convertDataSet(Statement stmt, JParamObject po) throws Exception {
		EFDataSet queryDataset = null;
		EFDataSet   newDataset = EFDataSet.getInstance();
		ResultSet           rs = null;
		String          strSql = ""; 
		EMPPageQuery pageQuery = (EMPPageQuery) po.getValue(EMPQueryParamEnum.PAGEQUERY, "");

		//先把数据合并
		strSql = " insert into " + msTableName + " (F_ID, F_XMBH,F_CPBH,F_SCSL, F_CCSL)"
		       + " select '1', F_XMBH, F_CPBH, ifnull(round(sum(round(F_SCSL,2)),2),0),ifnull(round(sum(round(F_CCSL,2)),2),0)"
		       + " from " + msTableName
		       + " where F_ID = '0' group by F_XMBH, F_CPBH";
		stmt.execute(strSql);
		
		//删掉合并前的数据
		strSql = "Delete From " + msTableName + " Where F_ID = '0'";
	    stmt.executeUpdate(strSql);
	    
		//更新项目名称
		strSql = " update " + msTableName + " TEMP"
	           + " INNER JOIN HTXMZD TEMP1 ON TEMP.F_XMBH = TEMP1.F_XMBH set TEMP.F_XMMC = TEMP1.F_XMMC" ;
		stmt.execute(strSql);

		//更新产品名称
		strSql = " update " + msTableName + " TEMP"
	           + " INNER JOIN HTCPZD TEMP1 ON TEMP.F_CPBH = TEMP1.F_CPBH set TEMP.F_CPMC = TEMP1.F_CPMC" ;
		stmt.execute(strSql);
		
		//更新剩余数量
		strSql = " update " + msTableName + " set F_SYSL = ifnull(round(ifnull(round(F_SCSL,2),0) - ifnull(round(F_CCSL,2),0),2),0)";
		stmt.execute(strSql);
		
		strSql = " select F_XMBH, F_XMMC, F_CPBH, F_CPMC, ifnull(round(F_SCSL,2),0) as F_SCSL, ifnull(round(F_CCSL,2),0) as F_CCSL, ifnull(round(F_SYSL,2),0) as F_SYSL from " 
			   + msTableName + " order by F_XMBH, F_CPBH";
		rs = stmt.executeQuery(strSql);
		queryDataset = DataSetUtils.resultSet2DataSet(rs, queryDataset);

		if(pageQuery == null) return queryDataset;
		
		pageQuery.setTotalCount(queryDataset.getRowCount());
		newDataset = EMPLimitConvertUtil.getDataSetLimit(queryDataset, pageQuery.getPageNum(), pageQuery.getNumPerPage());
		return newDataset;
	}
}
